﻿using System;
using System.IO;
using System.Web;

namespace Rio.Applications.Web
{
    public partial class FileDownload : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            // Retreive the user logged
            // Retreive the FullPathFile
            string fullPathFileDownloadFromSrv = Server.UrlDecode(Request.QueryString["fp"]);
            string originalFileName = Server.UrlPathEncode(Server.UrlDecode(Request.QueryString["name"]));

            // Test if the file exists
            NetBay.Core.Log.LogManager.Instance().LogInfo(" --------------------------------------------- " + fullPathFileDownloadFromSrv + "---------------------------------");
            if (File.Exists(fullPathFileDownloadFromSrv))
            {
                // Retreive the file
                FileInfo file = new FileInfo(fullPathFileDownloadFromSrv);
                // Build the response
                Response.ClearContent();
                Response.AddHeader("Content-Disposition", "attachment; filename=" + originalFileName);
                Response.AddHeader("Content-Length", file.Length.ToString());
                Response.ContentType = MimeType(originalFileName);
                Response.TransmitFile(file.FullName);
                Response.Flush(); 
                Response.Close();
                //Response.End();
            }
        }

        /// <summary>
        /// Retreive the "Content Type" of filename
        /// </summary>
        /// <param name="filename">FileName</param>
        /// <returns></returns>
        private string MimeType(string filename)
        {
            string mime = "application/octetstream";
            string extension = Path.GetExtension(filename);

            if (extension != null)
            {
                string ext = extension.ToLower();

                Microsoft.Win32.RegistryKey rk = Microsoft.Win32.Registry.ClassesRoot.OpenSubKey(ext);

                if (rk != null && rk.GetValue("Content Type") != null)
                    mime = rk.GetValue("Content Type").ToString();
            }

            return mime;
        }
    }
}